package ch02.demo;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class XMLParse {
    Document doc=null;
    public void getDocument(){
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        try{
            DocumentBuilder builder=factory.newDocumentBuilder();
            doc=builder.parse("src/main/java/ch02/demo/Parse.xml");
        }catch (ParserConfigurationException e){
            e.printStackTrace();
        }catch (SAXException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void showInfo(){
        NodeList nodeList=doc.getElementsByTagName("Brand");
        for (int i=0;i<nodeList.getLength();i++){
            Node brand=nodeList.item(i);
            Element brandEle= (Element) brand;
            String brandStr=brandEle.getAttribute("name");
            NodeList types=brandEle.getChildNodes();
            for (int j=0;j<types.getLength();j++){
                Node type=types.item(j);
                if(type.getNodeType()==Node.ELEMENT_NODE){
                    Element typeEle=(Element) type;
                    String typeStr=typeEle.getAttribute("name");
                    System.out.println("手机:"+brandStr+typeStr);
                }
            }
        }
    }

    public static void main(String[] args) {
        XMLParse parse=new XMLParse();
        parse.getDocument();
        parse.showInfo();
    }
}
